<template>
  <a-drawer
    v-model:visible="vdata.visible"
    :title="vdata.isAdd?'新建自建渠道码':'修改自建渠道码'"
    width="40%"
    :mask-closable="false"
    @close="onClose"
  >
    <a-tabs v-model:activeKey="vdata.singleActiveKey" @change="changehdler">
      <a-tab-pane :key="1" tab="单个自建渠道码生成" />
      <a-tab-pane v-if="vdata.isAdd" :key="2" tab="多个自建渠道码生成" />
    </a-tabs>

    <div v-if="vdata.singleActiveKey === 1" class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item label="渠道码归属" name="agentNo4" :wrapper-col="{ span: 16 }">
              <GzTreeSelect ref="gzThreeRef" v-model:value="vdata.saveObject['agentNo4']" :disabled="!vdata.isAdd" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="微信公众号" name="appId" :wrapper-col="{ span: 16 }">
              <a-select v-model:value="vdata.saveObject['appId']" :disabled="!vdata.isAdd" :options="officialList " placeholder="请选择微信公众号" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item
              label="渠道码名称"
              name="channelName"
              :wrapper-col="{ span: 16 }"
            >
              <a-input
                v-model:value="vdata.saveObject['channelName']"
                placeholder="请输入渠道码名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="12">
            <a-form-item label="是否开启距离限制" name="isDistanceLimit" :wrapper-col="{ span: 16 }">
              <a-switch v-model:checked="vdata.saveObject.isDistanceLimit" />
            </a-form-item>
          </a-col>
          <a-col v-if="vdata.saveObject.isDistanceLimit" :span="12">
            <a-form-item label="限制距离/米" name="distanceLimit" :wrapper-col="{ span: 16 }">
              <a-input-number v-model:value="vdata.saveObject['distanceLimit']" placeholder="请输入距离" style="width: 100%" />
            </a-form-item>
          </a-col>
        </a-row>
        <!-- 引入地图组件  -->
        <GzAmap ref="gzAmapRef" />
      </a-form>
    </div>
    <div v-else class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="rules"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item label="微信公众号" name="appId" :wrapper-col="{ span: 16 }">
              <a-select v-model:value="vdata.saveObject['appId']" :options="officialList" placeholder="请选择微信公众号" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item name="fileList">
              <template #label>
                <span style="margin-right: 20px">文件上传</span>
                <a class="item" type="link" style="padding: 4px 0" href="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/template/self_built_channel_template.xlsx">
                  自建渠道码批量生成模板下载
                </a>
              </template>
              <a-upload-dragger
                v-model:fileList="vdata.saveObject['fileList']"
                :action="vdata['action']"
                :data="vdata.formParams"
                :maxCount="1"
                accept=".xlsx, .xls"
                name="file"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
                <p class="ant-upload-hint">
                  <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-col>
        </a-row>
        <div>
          <p>批量生成校验结果查询</p>
          <div style="display: flex;justify-content: space-evenly;">
            <span>校验成功:{{ uploadObject.successCount }}条</span>
            <span>检验失败:{{ uploadObject.failCount }}条</span>
          </div>
        </div>
        <a-button style="margin-top: 30px;" type="primary" @click="download">下载导入反馈明细</a-button>
      </a-form>
    </div>
    <div class="drawer-btn-center">
      <a-button v-if="vdata.singleActiveKey === 1" type="primary" :loading="vdata.btnLoading" @click="onSubmit"><check-outlined />新增渠道</a-button>
    </div>
  </a-drawer>
</template>
<script lang="ts" setup>
import { ref, reactive, computed, getCurrentInstance, defineExpose, watch,nextTick,onMounted } from 'vue'
import * as XLSX from 'xlsx'
import { $getAgentWxList } from '@/api/activityManage/activityCreate/index'
import{$addOneSelfBuild,$selfBuildDetail,$updateOneSelfBuild,$importSelfBuildFile}from '@/api/channel/index'
import {$getUploadFormParams} from '@/api/components/GzUpload/index'
import { useAgentStore } from '@/store/modules/agent'
const agentInfoStore = useAgentStore().agentInfo
const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties
const props = defineProps({
  callbackFunc: { type: Function, default: () => () => ({}) }
})
const gzAmapRef = ref()

const formRef = ref()
const gzThreeRef = ref()
// 数据源
const vdata: any = reactive({
  singleActiveKey: 1, // 单OR多
  fileList: [], //上传文件列表
  saveObject: {},
  visible: false, //是否显示
  action: '', //上传地址
})


const rules: any = {
  fileList: [{ required: true, message: '请上传文件', trigger: 'change' }],
  agentNo4: [{ required: true, message: '请选择渠道码归属', trigger: 'change' }],
  appId: [{ required: true, message: '请选择公众号', trigger: 'change' }],
  channelName: [{ required: true, message: '请填写渠道码名称', trigger: 'blur' }],
  distanceLimit: [{ required: true, message: '请填写距离', trigger: 'blur' }],
}
// 查询机构小程序/公众号列表接口  0微信公众号   1微信小程序 
const officialList = ref([])
async function getAgentWxList(){
  const res = await $getAgentWxList({ agentNo:agentInfoStore.agentNo, type: 0 })
  officialList.value = res.map(item => ({ label: item.name, value: item.appId }))
  
}


/**
 * 文件上传
 */
function beforeUpload(file) {
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'upload').then((res) => {
    vdata.action = res.formActionUrl // action
    vdata.formParams = res.formParams //表单组件
    vdata.saveObject.ossFileUrl = res.ossFileUrl
  })
}
const uploadObject = ref(
  {
    successCount:null,
    failCount:null,
    reasonUrl:null,
  }
) as any
function uploadChange(info) {
  if (info.file.status === 'error') {
    // 上传异常
    vdata.saveObject.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }

  if (info.file.status === 'done') {
    // 上传成功
    $importSelfBuildFile({appId:vdata.saveObject.appId,ossFileUrl:vdata.saveObject.ossFileUrl}).then((res)=>{
      uploadObject.value.successCount = res.successCount
      uploadObject.value.failCount = res.failCount
      uploadObject.value.reasonUrl = res.reasonUrl
    })
  }
}
function download(){
  if(uploadObject.value.reasonUrl){
  downloadFile(uploadObject.value.reasonUrl,'反馈明细')
  }else{
  $infoBox.message.error('请先上传文件，才可以导出反馈结果')
  }
}

function downloadFile(url, filename) {
  const a = document.createElement('a')
  a.href = url
  a.download = filename || 'download'
  document.body.appendChild(a)
  a.click()
  document.body.removeChild(a)
}


/**
 * 展开
 */
  let initMapData : any = {}
  async function show(activityChannelId) {
    getAgentWxList()
    vdata.saveObject.activityChannelId = activityChannelId
    vdata.isAdd = activityChannelId?false:true
    vdata.visible = true
  if(vdata.isAdd){
    // 显示地图信息
    nextTick(() => gzAmapRef.value.init(initMapData))
  }else{
  $selfBuildDetail({activityChannelId}).then(res=>{
    vdata.saveObject.appId = res.appId
      vdata.saveObject.agentNo4 = res.agentNo4
      vdata.saveObject.channelName = res.channelName
      vdata.saveObject.isDistanceLimit = res.isDistanceLimit==1?true:false
      vdata.saveObject.distanceLimit = res.distanceLimit
      if(res.areaCode && res.areaCode.length){
        initMapData.areacode = JSON.parse(res.areaCode)
        initMapData.lnglat = res.longitude + ',' + res.latitude
        initMapData.address = res.address
        initMapData.areacodeNames = JSON.parse(res.areaName)
      }
      // 显示地图信息
      nextTick(() => gzAmapRef.value.init(initMapData))
    })
  }

}

function onSubmit() {
    let mapData = gzAmapRef.value.getMapData()
  if (!mapData || mapData.areacode.length == 0 || !mapData.address || !mapData.lnglat) {
    return $infoBox.message.error('请选择地理位置')
  }
  if (mapData.lnglat.indexOf(',') < 0) {
    return $infoBox.message.error('请输入正确的经纬度')
  }
    vdata.saveObject.location ={
    longitude:mapData.lnglat.split(',')[0],
    latitude:mapData.lnglat.split(',')[1]
  }
  vdata.saveObject.address = mapData.address
  vdata.saveObject.areaCode = JSON.stringify(mapData.areacode)
  vdata.saveObject.areaName = JSON.stringify(mapData.areacodeNames)
   formRef.value.validate().then(() => {

    vdata.btnLoading = true
    let reqObject = Object.assign({}, vdata.saveObject) // 请求数据
    if(vdata.isAdd){
    $addOneSelfBuild(reqObject).then(res => {
      vdata.visible = false
      props.callbackFunc() // 刷新列表
       onClose()
      $infoBox.message.success('生成成功')
    }).finally(() => {
       vdata.btnLoading = false
    })
    }else{
      $updateOneSelfBuild(reqObject).then(res => {
      onClose()
      props.callbackFunc() // 刷新列表
      vdata.btnLoading = false
      $infoBox.message.success('编辑成功')
    }).finally(() => {
       vdata.btnLoading = false
    })
    }

  })
  
}
function onClose() {
  vdata.visible = false
  // 重置数据
  vdata.singleActiveKey = 1
  vdata.fileList = []
  vdata.action = ''
  vdata.saveObject = {}
  initMapData = {}
  uploadObject.value = {
      successCount:null,
    failCount:null,
    reasonUrl:null,
  }
  formRef.value.resetFields()
}
// 每次切换重置数据 
function changehdler(key) {
  vdata.singleActiveKey = key
  // 重置表单
  vdata.saveObject = {}
  vdata.fileList = []
  vdata.action = ''
  vdata.saveObject = {}
  initMapData = {}
   uploadObject.value = {
      successCount:null,
    failCount:null,
    reasonUrl:null,
   }
  nextTick(() => gzAmapRef.value.init(initMapData))
  formRef.value.resetFields()
}
defineExpose({
  show,
})
</script>
<style lang="less" scoped>
.choseText {
  color: #1890ff;
}

.container {
  width: 100%;
  padding-bottom: 30px;

  .step {
    width: 30%;
  }

  .textMerchant {
    width: 60%;
    margin-bottom: 30px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .merchantResult {
    .information {
      display: flex;
      justify-content: right;
      margin-top: 30px;
    }
  }

  .form {
    margin: 30px;
    justify-content: center;
    overflow-y: auto;

    &::-webkit-scrollbar {
      display: none;
    }
  }
}

/deep/ .ant-upload-list-item-name {
  width: auto;
  flex-grow: 1 !important;
}

</style>